import datetime
import json
import re

from django.contrib.auth import login, authenticate, logout
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
from django.views import View

from lovehome_pro.utils.Loginmixin import LoginMixin
from xyuzi.models import Area, Facility, House, User, Order, HouseImage
from django_redis import get_redis_connection


class LoginView(View):
    """登录,判断登录,退出登录"""

    def post(self, request):
        """登录"""
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')

        if not all([mobile, password]):
            return JsonResponse({
                "errno": '400',
                'errmsg': '缺少必传参数'
            })
        # 重写方法 使 authenticate 中username指向mobile 从而实现手机号登录
        user = authenticate(username=mobile,
                            password=password)
        if not user:
            return JsonResponse({
                "errno": '400',
                'errmsg': '手机号或密码错误'
            })

        # 使用自带login函数实现状态保持(session)
        login(request, user)

        return JsonResponse({
            "errno": "0",
            "errmsg": "登录成功"
        })

    def get(self, request):

        """获取username右上角展示"""
        if request.user.is_authenticated:
            data = {
                'name': request.user.username,
                'user_id': request.user.id
            }
            return JsonResponse({
                "errno": "0",
                "errmsg": "已登录",
                'data': data
            })
        else:
            return JsonResponse({
                "errno": "4101",
                "errmsg": "未登录"
            })

    def delete(self, request):
        """退出登录接口"""
        # 使用自带logout 清除状态保持 session
        logout(request)
        return JsonResponse({
            'errno': '0',
            'errmsg': '已登出'
        })


class HouseReleaseView(View):
    """发布房源"""

    def post(self, request):
        dict = json.loads(request.body.decode())
        title = dict.get('title')
        price = dict.get('price')
        area_id = dict.get('area_id')
        address = dict.get('address')
        room_count = dict.get('room_count')
        acreage = dict.get('acreage')
        unit = dict.get('unit')
        capacity = dict.get('capacity')
        beds = dict.get('beds')
        deposit = dict.get('deposit')
        min_days = dict.get('min_days')
        max_days = dict.get('max_days')
        facility = dict.get('facility')
        if not request.user.real_name and not request.user.id_card:
            return JsonResponse({
                'errno': '400',
                'errmsg': '该用户没有实名'
            })

        if not all(
                [title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days,
                 facility]):
            return JsonResponse({
                'errno': '400',
                'errmsg': '缺少必传参数'
            })

        try:
            area = Area.objects.get(id=area_id)
        except Exception as e:
            return JsonResponse({
                'errno': '400',
                'errmsg': '传入城区id错误'
            })

        try:
            facility = Facility.objects.filter(id__in=facility)
        except Exception as e:
            return JsonResponse({
                'errno': '400',
                'errmsg': '传入facility的id错误'
            })

        try:
            house = House.objects.create(
                user=request.user,
                area=area,
                title=title,
                price=price,
                address=address,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                beds=beds,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days,
            )
            house.facility.add(*facility)
            house.save()

        except Exception as e:
            return JsonResponse({
                'errno': '400',
                'errmsg': '保存失败'
            })

        return JsonResponse({
            "errno": "0",
            "errmsg": "发布成功",
            "data": {
                "house_id": house.id
            }
        })

    def get(self, request):
        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk')
        p = request.GET.get('p')
        if not all([aid, sd, ed, sk]):
            return JsonResponse({
                'errno': '400',
                'errmsg': '缺少必传参数'
            })
        p = 1 if not p else p
        start = datetime.datetime.strptime(sd, '%Y-%m-%d')
        end = datetime.datetime.strptime(ed, '%Y-%m-%d')

        # 获取天数
        result = (end - start).days

        dict = {
            'new': 'update_time',
            'booking': 'order_count',
            'price-inc': 'price',
            'price-des': '-price',
        }
        sk_data = dict.get(sk, 'new')
        try:
            houses = House.objects.filter(area_id=aid).order_by(sk_data)
        except Exception as e:
            return JsonResponse({
                'errno': '400',
                'errmsg': '缺少必传参数'
            })
        house_list = []
        url_start = 'http://qa77xtdyw.bkt.clouddn.com/'
        for house in houses:
            if result < house.min_days and result > house.max_days:
                continue
            house_list.append({
                'address': house.address,
                'area_name': house.area.name,
                "ctime": house.create_time,
                "house_id": house.id,
                "img_url": url_start + str(house.index_image_url),
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": url_start + str(house.user.avatar)
            })
        data = {
            'houses': house_list,
            'total_page': 1  # 手机页面一页就够了
        }
        return JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data': data
        })


class HouseDetails(View):
    """房屋详细信息"""

    def get(self, request, house_id):
        try:
            house = House.objects.get(id=house_id)
            orders = Order.objects.filter(house_id=house_id)
            house_images = HouseImage.objects.filter(house_id=house_id)
            facilities = house.facility.all()
        except Exception as e:
            return JsonResponse({
                'errno': '400',
                'errmsg': '查询房屋id不存在'
            })

        comments = []
        for order in orders:
            try:
                user = User.objects.get(id=order.user_id)
            except Exception as e:
                return JsonResponse({
                    'errno': '400',
                    'errmsg': '查询数据库失败'
                })
            comments.append({
                'comment': order.comment,
                'ctime': order.update_time,
                'user_name': user.username
            })

        img_urls = []
        for house_image in house_images:
            img_urls.append('http://qa77xtdyw.bkt.clouddn.com/' + str(house_image.url))

        facilities_list = []
        for facilitie in facilities:
            facilities_list.append(facilitie.id)

        house_dict = {
            'acreage': house.acreage,
            'address': house.address,
            'beds': house.beds,
            'capacity': house.capacity,
            "comments": comments,
            "deposit": house.deposit,
            "facilities": facilities_list,
            "hid": house_id,
            "img_urls": img_urls,
            "max_days": house.max_days,
            "min_days": house.min_days,
            "price": house.price,
            "room_count": house.room_count,
            "title": house.title,
            "unit": house.unit,
            "user_avatar": "http://qa77xtdyw.bkt.clouddn.com/" + str(house.user.avatar),
            "user_id": house.user_id,
            "user_name": house.user.username
        }
        user_id = request.user.id if request.user.is_authenticated else -1

        return JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data': {
                'house': house_dict,
                'user_id': user_id
            }
        })
